package com.sky.service.impl;

import com.sky.constant.JwtClaimsConstant;
import com.sky.entity.User;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.service.UserService;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * 用户服务实现类
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource(name = "userMapper")
    UserMapper userMapper; // 用户数据操作接口
    @Resource(name = "jwtProperties")
    JwtProperties jwtProperties; // JWT配置属性

    /**
     * 用户登录
     * 根据openid查询用户，如果不存在则创建新用户并登录。
     *
     * @param openid 用户的唯一标识
     * @return UserLoginVO 包含登录成功后的用户信息和JWT令牌
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserLoginVO login(String openid) {
        // 根据openid查询用户
        User user = userMapper.selUserByOpenid();

        //用户不存在，添加用户
        if (user == null) {
            user = User.builder()
                    .openid(openid)
                    .createTime(LocalDateTime.now())
                    .build();
            userMapper.addUser(user);
            log.info("新用户注册成功");
        }

        // 生成JWT令牌
        HashMap<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);

        // 构建用户登录详情返回对象
        return UserLoginVO.builder()
                .id(user.getId())
                .openid(user.getOpenid())
                .token(token)
                .build();
    }

}
